package com.eshin;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

import com.eshin.security.Reader;
import com.eshin.security.ReaderRepository;

/*@RestController
@EnableAutoConfiguration*/
@Controller
@RequestMapping("/hello")
public class Hello {
	
	
	private ReadingListRepository readingListRepository;
	@Autowired
	private ReaderRepository readerRepository;
	@Autowired
	public Hello(ReadingListRepository readingListRepository) {
		this.readingListRepository = readingListRepository;
	}

	/*@RequestMapping("/")
	String home() {
		return "Hello World!";
	}*/

	/*@RequestMapping("/hello/{myName}")
	String index(@PathVariable String myName) {
		return "Hello " + myName + "!!!";
	}*/

	@RequestMapping(value = "/{reader}", method = RequestMethod.GET)
	public String readersBooks(@PathVariable("reader") String reader, Model model) {
		List<Book> readingList = readingListRepository.findByReader(reader);
		if (readingList != null) {
			model.addAttribute("books", readingList);
		}
		
		return "readingList";
	}

	@RequestMapping(value = "/{reader}", method = RequestMethod.POST)
	public String addToReadingList(@PathVariable("reader") String reader, Book book) {
		book.setReader(reader);
		Reader readerd = new Reader();
		readerd.setFullname(reader);
		readerd.setUsername(reader);
		readerRepository.save(readerd);
		readingListRepository.save(book);
		return "redirect:/hello/{reader}";
	}

	@RequestMapping(value = "/test", method = {RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody DeferredResult<String> testNull(){
		DeferredResult<String> result = new DeferredResult<String>();
		System.out.println("i am null");
		result.setResult("i am null");
		return result;
		
	}
}
